package com.hj.springframework3.io;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.time.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.function.Function;

/**
 * @Author : hujing
 * @Date: 2025/7/4 9:31
 * @Description: 属性解析器
 */
public class PropertyResolver {
    Logger logger = LoggerFactory.getLogger(getClass());
    Map<String, String> properties = new HashMap<>();
    Map<Class<?>, Function<String, Object>> converters = new HashMap<>();

    public PropertyResolver(Properties props) {
        // 加载系统属性
        this.properties.putAll(System.getenv());
        // 加载传递进来的属性
        props.stringPropertyNames().forEach(key -> {
            this.properties.put(key, props.getProperty(key));
        });

        // 注册默认的转换器
        converters.put(String.class, s -> s);
        converters.put(boolean.class, Boolean::parseBoolean);
        converters.put(Boolean.class, Boolean::parseBoolean);

        converters.put(byte.class, Byte::parseByte);
        converters.put(Byte.class, Byte::parseByte);

        converters.put(short.class, Short::parseShort);
        converters.put(Short.class, Short::parseShort);

        converters.put(int.class, Integer::parseInt);
        converters.put(Integer.class, Integer::parseInt);

        converters.put(long.class, Long::parseLong);
        converters.put(Long.class, Long::parseLong);

        converters.put(float.class, Float::parseFloat);
        converters.put(Float.class, Float::parseFloat);

        converters.put(double.class, Double::parseDouble);
        converters.put(Double.class, Double::parseDouble);

        converters.put(LocalDate.class, LocalDate::parse);
        converters.put(LocalTime.class, LocalTime::parse);
        converters.put(LocalDateTime.class, LocalDateTime::parse);
        converters.put(ZonedDateTime.class, ZonedDateTime::parse);
        converters.put(Duration.class, Duration::parse);
        converters.put(ZoneId.class, ZoneId::of);
    }

    /**
     * 根据key获取属性值
     * @param key
     * @return
     */
    @Nullable
    public String getProperty(String key) {
        PropertyExpr keyExpr = parsePropertyExpr(key);
        if (keyExpr != null) {// 存在表达式
            if (keyExpr.defaultValue != null) {// 有默认值
                return getProperty(keyExpr.key, keyExpr.defaultValue);
            }else{
                return getRequiredProperty(keyExpr.key);
            }
        }
        // 获取非表达式的属性值
        String value = this.properties.get(key);
        if (value != null){
            return parseValue(value);
        }
        return value;
    }

    /**
     * 根据key获取属性值，并转换成targetType类型
     * @param key
     * @param targetType
     * @return
     * @param <T>
     */
    public <T> T getRequiredProperty(String key,Class<T> targetType){
        return getProperty(key,targetType);
    }
    
    @Nullable
    public <T> T getProperty(String key,Class<T> targetType){
        String value = getProperty(key);
        if (value == null){
            return null;
        }
        return convert(targetType,value);
    }

    public String getProperty(String key, String defaultValue) {
        String value = getProperty(key);
        return value == null ? parseValue(defaultValue) : value;
    }

    /**
     * 解析value，如果value中有表达式，则进一步解析
     * @param value
     * @return
     */
    String parseValue(String value) {
        PropertyExpr expr = parsePropertyExpr(value);
        if (expr == null) {
            return value;
        }
        if (expr.defaultValue != null) {
            return getProperty(expr.key, expr.defaultValue);
        } else {
            return getRequiredProperty(expr.key);
        }
    }
    
    public String getRequiredProperty(String key){
        String value = getProperty(key);
        return Objects.requireNonNull(value,"未找到属性:"+key+"的值");
    }

    /**
     * 解析属性表达式
     * @param key
     * @return
     */
    private PropertyExpr parsePropertyExpr(String key) {
        if (key.startsWith("${") && key.endsWith("}")) {
            int n = key.indexOf(":");
            if (n == -1) {//没有默认值
                String k = key.substring(2, key.length() - 1);
                return new PropertyExpr(k, null);
            } else {
                String k = key.substring(2, n);
                return new PropertyExpr(k, key.substring(n + 1, key.length() - 1));
            }
        }
        return null;
    }

    /**
     * 类型转换器,将value转换为clazz类型
     * @param clazz
     * @param value
     * @return
     * @param <T>
     */
    <T> T convert(Class<?> clazz,String value){
        Function<String, Object> fn = this.converters.get(clazz);
        if (fn == null  ){
            throw new IllegalArgumentException("不支持的类型:"+clazz.getName());
        }
        return (T)fn.apply(value);
    }
}

@Data
class PropertyExpr {
    String key;
    String defaultValue;

    public PropertyExpr(String key, String defaultValue) {
        this.key = key;
        this.defaultValue = defaultValue;
    }
}
